<?php
/**
 *  
 * @package package_name
 * @author Mervin.Wong<mervin0502@163.com>
 * @copyright
 * @license  http://www.apache.org/licenses/LICENSE-2.0
 * @version 0.1.0
 * @date 2013-3-7下午6:58:24
 *
 */
 /**
  * CanGoo Attachment Controller
  * 附件管理器
  * @package admin
  * @subpackage controllers
  */
 class Attachment extends CI_Controller{
 	
 	/**
 	 * 构造函数
 	 */
 	public function __construct(){
 		parent::__construct();
 		$this->load->helper('url');
 		$this->load->helper('form');
 		$this->load->helper('date');
 		$this->load->helper('common');
 		$this->load->library('common');
 		$this->load->library('session');
 		$this->load->library('pagination');
 		$this->load->model('common_model');
  		if(!$this->common_model->is_login($this->session->userdata('session_id'))){
  			redirect(site_url('index/login', 'refresh'));
  		}
 		
 		$this->load->model('attachment_model');
 		
 		$this->load->library('form_validation');
 		$this->form_validation->set_rules('attach_name','附件名称','trim|required|min_length[5]|max_length[100]|xss_clean');
 		$this->form_validation->set_rules('attach_slug','附件别名','trim|required|min_length[5]|max_length[100]|xss_clean');
 		$this->form_validation->set_rules('attach_description','附件描述','trim|xss_clean');
 		
 	}
 	
 	public function index(){
		redirect(site_url('attachment/listing'));
 	}
 	/**
 	 * 附件列表
 	 */
 	public function listing($page = 1){
 		$total = $this->attachment_model->get_num('aid', 'attachment', '');
 		$per = 2;
 		//$data['pagination'] = $this->common->pagination_set(site_url('attachment/listing'), $total, $per, 3);
 		$data['pagination'] = pagination_set(site_url('attachment/listing'), $total, $per, 3);
 		
 		$data['attach_table'] = '<div id="single_list">'.$this->_table($page, $per).'</div>';
 		$this->load->view('attachment_view', $data); 		
 	}
 	
 	
 	/**
 	 * 编辑附件
 	 */
 	public function edit($aid = 0){
 		if($this->input->post('is_submit') == 'ok'){
			if($this->form_validation->run() == FALSE){
				//检测没有通过
				$action = 'attachment/edit/'.$aid;
				$values['name'] = set_value('attach_name');
				$values['slug'] = set_value('attach_slug');
				$values['description'] = set_value('attach_description');
				
				$row = $this->attachment_model->get_one(array('type', 'data', 'addTime'), 'attachment', array('aid'=>$aid));

				$values['type'] = $row['type'];
				$values['addTime'] = $row['addTime'];
				
				$data = unserialize($row['data']);
				$values['url'] = $data['url'];
				$values['mime'] = $data['mime'];
				$values['size'] = $this->_file_size($data['size']).((!isset($data['image_width']) && empty($data['image_width']))?'':'&nbsp;'.$data['image_width'].'X'.$data['image_height']);
				
				$data['attach_info_form'] = $this->_form($action, $values);
				$data['attach_info_error'] = validation_errors();
				$this->load->view('attachment_view', $data);	
			}else{
				//提交到数据库
				$values['name'] = $this->input->post('attach_name');
				$values['slug'] = $this->input->post('attach_slug');
				$values['description'] = $this->input->post('attach_description');
				$this->attachment_model->update($values, 'attachment', array('aid'=>$aid));
				redirect(site_url('attachment/listing'));
			}
		}else{
			if($aid != 0){
				$row = $this->attachment_model->get_one(array('type', 'name', 'slug', 'description', 'data', 'addTime'), 'attachment', array('aid'=>$aid));
				$action = 'attachment/edit/'.$aid;
				$values['type'] = $row['type'];
				$values['name'] = $row['name'];
				$values['slug'] = $row['slug'];
				$values['description'] = $row['description'];
				$values['addTime'] = $row['addTime'];
				
				$data = unserialize($row['data']);
				$values['url'] = $data['url'];
				$values['mime'] = $data['mime'];
				$values['size'] = $this->_file_size($data['size']).((!isset($data['image_width']) && empty($data['image_width']))?'':'&nbsp;'.$data['image_width'].'X'.$data['image_height']);
				
				$data['attach_info_form'] = $this->_form($action, $values);
				$this->load->view('attachment_view', $data);
			}else{
				redirect(site_url('attachment/listing'));
			}
		}

 	}
 	
 	/**
 	 * 添加附件
 	 */
 	public function add($attch_type = 'file'){
 		
 		//第一次上传
 		if($this->input->post('is_upload') == 'ok'){
 			
 			/**
 			 * 附件归档：附件类型/月份/文件名
 			 */
 			$root = $this->input->server('DOCUMENT_ROOT');
 			$attch_dir = '/public/uploads/'.$this->input->post('attach_type').'/'.mdate('%Y%m', now());
 			$attach_path = $root.$attch_dir;
 			$this->_create_file($attach_path);
 			
	 		$config['upload_path'] = $attach_path;
	 		$attach_type = $this->config->item('attach_type');
	 		$config['allowed_types'] = $attach_type[$this->input->post('attach_type')];
	 		$config['overwrite'] = true;
	 		$config['max_size'] = 0;
	 		$config['max_width'] = 0;
	 		$config['max_height'] = 0;
	 		$config['max_filename'] = 0;
	 		$config['remove_spaces'] = true;
	 		$this->load->library('upload', $config);
			if(!$this->upload->do_upload('attach_upload')){
				//上传失败
				//$this->_show_msg($this->upload->display_errors());
				echo $this->upload->display_errors();
				//redirect(site_url('attachment/add'));
			}else{
				$data = $this->upload->data();
				//$action = 'attachment/edit';
				$values['uid'] = $this->session->userdata('uid');
				$values['name'] = $data['file_name'];
				$values['slug'] = $data['raw_name'];
				$values['description'] = '';
				$values['addTime'] = now();
				$values['modTime'] = now();
				$values['viewNum'] = 1;
				$values['commentNum'] = 0;
				$values['type'] = $this->input->post('attach_type');
				
				$attach_data['url'] = base_url($attch_dir.'/'.$data['file_name']);
				$attach_data['mime'] = $data['file_type'];
				$attach_data['size'] = round($data['file_size'], 2);
				if(!empty($data['image_width'])){
					$attach_data['image_width'] = $data['image_width'];
					$attach_data['image_height'] = $data['image_height'];
				}
				$values['data'] = serialize($attach_data);
				$insert_id = $this->attachment_model->insert($values, 'attachment');
				redirect(site_url('attachment/edit/'.$insert_id));
			}
 		}else{
	 		$form = form_open_multipart(site_url('attachment/add'), array('name'=>'attach_form', 'id'=>'attach_form', 'class'=>'attach_form'));
	 		$form .= '<p>';
	 		$form .= form_upload(array('name'=>'attach_upload', 'id'=>'attach_upload', 'class'=>'attach_upload'));
	 		$form .= form_hidden('attach_type', $attch_type);
	 		$form .= form_hidden('is_upload', 'ok');
	 		$form .= form_submit('attach_submit', '上传');
	 		$form .= form_close();
	 		$data['attach_add_form'] = $form;
	 		$this->load->view('attachment_view', $data); 			
 		}
 	}
 	
 	/**
 	 * 删除附件
 	 */
 	public function del($aid){
 		$this->attachment_model->delete('attachment', array('aid'=>$aid));
 		//删除文章和附件的映射关系
 		$this->attachment_model->delete('attach_map', array('aid'=>$aid));
 		redirect(site_url('attachment/listing'));
 	}
 	
 	/**
 	 * 附件信息
 	 */
 	private function _form($action, $values){
 		
 		$form = form_open($action, array('name'=>'attach_form', 'id'=>'attach_form', 'class'=>'attach_form'));
 		$form .= '<div id="attach_form_left" >';
 		$form .='<p>';
 		$form .= form_label( '附件名称:', 'attach_name');
 		$form .= form_input(array('name'=>'attach_name', 'id'=>'attach_name', 'class'=>'attach_name','value'=>$values['name']));
 		$form .='</p><p>';
 		$form .= form_label('附件别名:', 'attach_slug');
 		$form .= form_input(array('name'=>'attach_slug', 'id'=>'attach_slug', 'class'=>'attach_slug', 'value'=>$values['slug']));
 		$form .='</p><p>';
 		$form .= form_label('附件描述:', 'attach_description' );
 		$form .= form_textarea(array('name'=>'attach_description', 'id'=>'attach_description', 'class'=>'attach_description', 'cols'=>55, 'rows'=>10, 'value'=>$values['description'] ));
 		$form .='</p><p>';
 		$form .= '附件缩略图';
 		$form .='</p>';
		$form .= '</div>';
		$form .= '<div id="attach_form_right">';
		$form .= '<p>';
		$form .= '<strong>上传时间:</strong>'.mdate('%Y-%m-%d %H:%i:%s', $values['addTime']);
 		$form .='</p><p>';
 		$form .= '<strong>文件URL:</strong>'.$values['url'];
 		$form .='</p><p>';
 		$form .= '<strong>文件类型:</strong>'.$values['type'];
 		$form .='</p><p>';
 		$form .= '<strong>MIME信息:</strong>'.$values['mime'];
 		$form .='</p><p>';
 		$form .= '<strong>文件大小:</strong>'.$values['size'];
 		$form .='</p><p>';
 		$form .= form_hidden('is_submit', 'ok');
 		$form .= form_reset('attach_reset', '重写');
 		$form .= form_submit('attach_submit', '提交');
 		$form .='</p>';
 		$form .= '</div>';
 		return $form;
 	}
   	/**
  	 * 附件列表
  	 * @access private
  	 * @return array 表格信息
  	 */
  	 private function _table($page, $per){
  	 	$this->load->library('table');
  	 	//模板
 		$tmpl = array (
            'table_open'          => '<table id="attach_table" border="0" cellpadding="4" cellspacing="0">',

            'heading_row_start'   => '<tr>',
            'heading_row_end'     => '</tr>',
            'heading_cell_start'  => '<th>',
            'heading_cell_end'    => '</th>',

            'row_start'           => '<tr class="t1">',
            'row_end'             => '</tr>',
            'cell_start'          => '<td>',
            'cell_end'            => '</td>',

            'row_alt_start'       => '<tr class="t2">',
            'row_alt_end'         => '</tr>',
            'cell_alt_start'      => '<td>',
            'cell_alt_end'        => '</td>',

            'table_close'         => '</table>'
        );
		$this->table->set_template($tmpl);
  	 	//标题栏
  	 	$this->table->set_heading('文件名','作者','所属文章','发布日期','操作');
  	 	$offset = ($page-1)*$per;
  	 	$attachs = $this->attachment_model->get_all(array('aid', 'name', 'uid', 'addTime'), 'attachment', '', $offset, $per);
  	 	$table = array();
  	 	$i = 0;
  	 	foreach($attachs as $attach){
  	 		$table[$i]['name'] = $attach['name'];
  	 		$user = $this->attachment_model->get_one('name', 'user', array('uid'=>$attach['uid']));
  	 		$table[$i]['user'] = $user['name'];
  	 		//$posts = $this->attachment_model->get_posts($attach['aid']);
  	 		$table[$i]['posts'] = '';
  	 		$table[$i]['addTime'] = mdate('%Y-%m-%d %H:%i:%s');
  	 		$table[$i]['operation'] = '<a href="'.site_url('attachment/edit/'.$attach['aid']).'" >编辑</a>';
  	 		$table[$i]['operation'] .= '<a href="'.site_url('attachment/del/'.$attach['aid']).'" >删除</a>';
  	 		$i++;
  	 	}
  	 	return $this->table->generate($table);
  	 }	
  	 
 	private function __show_msg($msg){
 		echo '<script type="text/javascript">alert('.$msg.')</script>';
 	}
 	
 	/**
 	 * 变换文件的大小
 	 * Kb, Mb, Gb
 	 */
 	private function _file_size($file_size){
 		if($file_size < 1024 ){
 			$return = $file_size.'Kb';
 		}else if($file_size < 1024*1024){
 			$return = round(($file_size / 1024), 2).'Mb';
 		}else {
 			$return = round(($file_size / (1024*1024)), 2).'Gb';
 		}
 		
 		return $return;
 	}
 	
 	private function _file_type($file_ext){
 		$file_ext = substr($file_ext, 1, strlen($file_ext));
 	
 		
 	}
 	
 	/**
 	 * 创建多接文件夹
 	 */
 	 private function _create_file($dir){
 	 	if(!is_dir($dir)){
 	 		if($this->_create_file(dirname($dir))){
 	 			mkdir($dir, 0777);
 	 			//chmod($dir, 0777);
 	 			return true;
 	 		}
 	 	}else{
 	 		return true;
 	 	}
 	 }
 	 

 }

/* End of file attachment.php */
/* Location:./admin/controllers/attachment.php */